package service

import (
	"errors"
	"strconv"

	"gitee.com/cyanbleeze/go-image-management/global"
	"gitee.com/cyanbleeze/go-image-management/internal/model"
)

type LikeRequest struct {
	PictureID uint `form:"picture_id" json:"picture_id,omitempty" binding:"required,min=1"`
}
type ToggleLikeRequest struct {
	PictureID uint `form:"picture_id" json:"picture_id,omitempty" binding:"required,min=1"`
}

type CountLikeRequest struct {
	PictureID uint `form:"picture_id" json:"picture_id,omitempty" binding:"required,min=1"`
}

func (svc *Service) ToggleLike(params *ToggleLikeRequest) error {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return errors.New("登录用户信息不存在")
	}
	like, getErr := svc.dao.GetLikeOrCreate(
		userID.(uint),
		params.PictureID,
	)
	if getErr != nil {
		return getErr
	}
	key := "like_count_" + strconv.Itoa(int(params.PictureID))
	_, err := global.RedisEngine.Get(svc.ctx, key).Result()
	if err == nil {
		if !like.State {
			global.RedisEngine.Incr(svc.ctx, key).Result()
		} else {
			global.RedisEngine.Decr(svc.ctx, key).Result()
		}
	}
	updateErr := svc.dao.UpdateLike(
		like.ID,
		!like.State,
	)
	return updateErr
}

func (svc *Service) GetLike(params *LikeRequest) (*model.Like, error) {
	userID, exist := svc.ctx.Get("userID")
	if !exist {
		return nil, errors.New("登录用户信息不存在")
	}
	return svc.dao.GetLikeOrCreate(
		userID.(uint),
		params.PictureID,
	)
}

func (svc *Service) CountLiked(params *CountLikeRequest) (int, error) {
	key := "like_count_" + strconv.Itoa(int(params.PictureID))
	val, err := global.RedisEngine.Get(svc.ctx, key).Result()
	if err != nil {
		cnt, err := svc.dao.CountLikesByPictureID(
			params.PictureID,
			true,
		)
		if err != nil {
			return 0, err
		}
		global.RedisEngine.Set(svc.ctx, key, cnt, 0).Result()
		return cnt, err
	}
	return strconv.Atoi(val)
}
